﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EasyLift.TMS.Web.Models;
using EasyLift.TMS.Web.Helpers;

namespace CoreBiz.Web.Controllers
{
    public class MissionDetailController : Controller
    {

        MissionDetailRepository repository = new MissionDetailRepository();
        //
        // GET: /MissionDetail/

        public ActionResult Index(int? page)
        {
            int pageSize = 10;
            var MissionDetails = repository.GetAllData();
            var paginatedMissionDetails = new PaginatedList<MissionDetail>(MissionDetails, page ?? 0, pageSize);
            return View("Index", paginatedMissionDetails);
        }

        public ActionResult Outbound()
        {
            return View("Outbound");
        }

        public ActionResult Inbound()
        {
            return View("Inbound");
        }

        public ActionResult MissionReturned()
        {
            return View("MissionReturned");
        }

        public ActionResult History()
        {
            return View("History");
        }

        public ActionResult QCPassRegister()
        {
            return View("QCPassRegister");
        }

        public ActionResult QCRejectedRegister()
        {
            return View("QCRejectedRegister");
        }

        public JsonResult GridData(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString, Int64 MissionID)
        {

            var allData = repository.GetAllData(sidx, sord, _search, searchField, searchOper, searchString, MissionID);

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = allData.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            var paginatedAllData = new PaginatedList<MissionDetail>(allData, pageIndex, pageSize);


            var JsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = (
                    from p in paginatedAllData
                    select new
                    {
                        id = p.MissionDetailID.ToString(),
                        cell = new string[] {
                            p.MissionDetailID.ToString().ToString(),
                            p.VehicleNumber,
                            p.LicensePlateNumber,
                            p.DriverCivilID,
                            p.DriverName,
                            p.TrailerNumber
                        }
                    }
                ).ToArray()
            };

            return Json(JsonData, JsonRequestBehavior.AllowGet);
        }



        public JsonResult GridOutboundData(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString)
        {

            var allData = repository.GetAllDataByMissionType(sidx, sord, _search, searchField, searchOper, searchString, "Outbound");

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = allData.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            var paginatedAllData = new PaginatedList<MissionDetail>(allData, pageIndex, pageSize);


            var JsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = (
                    from p in paginatedAllData
                    select new
                    {
                        id = p.MissionDetailID.ToString(),
                        cell = new string[] {
                            p.MissionDetailID.ToString().ToString(),
                            p.MissionHeader.TMR,
                            p.MissionHeader.MissionDate.ToString(),
                            p.DepartureDate.ToString(),
                            p.DepartureRemarks,
                            p.VehicleNumber,
                            p.LicensePlateNumber,
                            p.VehicleOutboundMilage.ToString(),
                            p.DriverCivilID,
                            p.DriverName,
                            p.TrailerNumber
                        }
                    }
                ).ToArray()
            };

            return Json(JsonData, JsonRequestBehavior.AllowGet);
        }


        public JsonResult GridInboundData(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString)
        {

            var allData = repository.GetAllDataByMissionType(sidx, sord, _search, searchField, searchOper, searchString, "Inbound");

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = allData.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            var paginatedAllData = new PaginatedList<MissionDetail>(allData, pageIndex, pageSize);


            var JsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = (
                    from p in paginatedAllData
                    select new
                    {
                        id = p.MissionDetailID.ToString(),
                        cell = new string[] {
                            p.MissionDetailID.ToString().ToString(),
                            p.MissionHeader.TMR,
                            p.MissionHeader.MissionDate.ToString(),
                            p.DepartureDate.ToString(),
                            p.DepartureRemarks,
                            p.VehicleNumber,
                            p.LicensePlateNumber,
                            p.VehicleReturnDate.ToString(),
                            p.VehicleReturnRemarks,
                            p.VehicleOutboundMilage.ToString(),
                            p.VehicleInboundMilage.ToString(),
                            p.DriverCivilID,
                            p.DriverName,
                            p.DriverReturnDate.ToString(),
                            p.DriverReturnRemarks,
                            p.TrailerNumber
                        }
                    }
                ).ToArray()
            };

            return Json(JsonData, JsonRequestBehavior.AllowGet);
        }


        public JsonResult GridMissionReturnedData(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString)
        {

            var allData = repository.GetAllDataByMissionType(sidx, sord, _search, searchField, searchOper, searchString, "MissionReturned");

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = allData.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            var paginatedAllData = new PaginatedList<MissionDetail>(allData, pageIndex, pageSize);


            var JsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = (
                    from p in paginatedAllData
                    select new
                    {
                        id = p.MissionDetailID.ToString(),
                        cell = new string[] {
                            p.MissionDetailID.ToString().ToString(),
                            p.MissionHeader.TMR,
                            p.MissionHeader.MissionDate.ToString(),
                            p.DepartureDate.ToString(),
                            p.DepartureRemarks,
                            p.VehicleNumber,
                            p.LicensePlateNumber,
                            p.VehicleReturnDate.ToString(),
                            p.VehicleReturnRemarks,
                            p.VehicleOutboundMilage.ToString(),
                            p.VehicleInboundMilage.ToString(),
                            p.DriverCivilID,
                            p.DriverName,
                            p.DriverReturnDate.ToString(),
                            p.DriverReturnRemarks,                            
                            p.VehicleQCRejectedDate.ToString(),
                            p.VehicleQCRejectedRemarks,
                            p.VehicleQCPassDate.ToString(),
                            p.VehicleQCPassRemarks,
                            p.TrailerNumber
                        }
                    }
                ).ToArray()
            };

            return Json(JsonData, JsonRequestBehavior.AllowGet);
        }


        public JsonResult GridHistoryData(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString)
        {

            var allData = repository.GetAllDataByMissionType(sidx, sord, _search, searchField, searchOper, searchString, "History");

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = allData.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            var paginatedAllData = new PaginatedList<MissionDetail>(allData, pageIndex, pageSize);


            var JsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = (
                    from p in paginatedAllData
                    select new
                    {
                        id = p.MissionDetailID.ToString(),
                        cell = new string[] {
                            p.MissionDetailID.ToString().ToString(),
                            p.MissionHeader.TMR,
                            p.MissionHeader.MissionDate.ToString(),
                            p.DepartureDate.ToString(),
                            p.DepartureRemarks,
                            p.VehicleNumber,
                            p.LicensePlateNumber,
                            p.VehicleReturnDate.ToString(),
                            p.VehicleReturnRemarks,
                            p.VehicleOutboundMilage.ToString(),
                            p.VehicleInboundMilage.ToString(),
                            p.DriverCivilID,
                            p.DriverName,
                            p.DriverReturnDate.ToString(),
                            p.DriverReturnRemarks,                            
                            p.VehicleQCRejectedDate.ToString(),
                            p.VehicleQCRejectedRemarks,
                            p.VehicleQCPassDate.ToString(),
                            p.VehicleQCPassRemarks,
                            p.TrailerNumber
                        }
                    }
                ).ToArray()
            };

            return Json(JsonData, JsonRequestBehavior.AllowGet);
        }


        public JsonResult GridQCPassRegisterData(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString)
        {

            var allData = repository.GetAllDataByMissionType(sidx, sord, _search, searchField, searchOper, searchString, "QCPassRegister");

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = allData.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            var paginatedAllData = new PaginatedList<MissionDetail>(allData, pageIndex, pageSize);


            var JsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = (
                    from p in paginatedAllData
                    select new
                    {
                        id = p.MissionDetailID.ToString(),
                        cell = new string[] {
                            p.MissionDetailID.ToString().ToString(),
                            p.MissionHeader.TMR,
                            p.MissionHeader.MissionDate.ToString(),
                            p.DepartureDate.ToString(),
                            p.DepartureRemarks,
                            p.VehicleNumber,
                            p.LicensePlateNumber,
                            p.VehicleReturnDate.ToString(),
                            p.VehicleReturnRemarks,
                            p.VehicleOutboundMilage.ToString(),
                            p.VehicleInboundMilage.ToString(),
                            p.DriverCivilID,
                            p.DriverName,
                            p.DriverReturnDate.ToString(),
                            p.DriverReturnRemarks,                            
                            p.VehicleQCRejectedDate.ToString(),
                            p.VehicleQCRejectedRemarks,
                            p.VehicleQCPassDate.ToString(),
                            p.VehicleQCPassRemarks,
                            p.TrailerNumber,
                        }
                    }
                ).ToArray()
            };

            return Json(JsonData, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GridQCRejectedRegisterData(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString)
        {

            var allData = repository.GetAllDataByMissionType(sidx, sord, _search, searchField, searchOper, searchString, "QCRejectedRegister");

            int pageIndex = Convert.ToInt32(page) - 1;
            int pageSize = rows;
            int totalRecords = allData.Count();
            int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

            var paginatedAllData = new PaginatedList<MissionDetail>(allData, pageIndex, pageSize);


            var JsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = (
                    from p in paginatedAllData
                    select new
                    {
                        id = p.MissionDetailID.ToString(),
                        cell = new string[] {
                            p.MissionDetailID.ToString().ToString(),
                            p.MissionHeader.TMR,
                            p.MissionHeader.MissionDate.ToString(),
                            p.DepartureDate.ToString(),
                            p.DepartureRemarks,
                            p.VehicleNumber,
                            p.LicensePlateNumber,
                            p.VehicleReturnDate.ToString(),
                            p.VehicleReturnRemarks,
                            p.VehicleOutboundMilage.ToString(),
                            p.VehicleInboundMilage.ToString(),
                            p.DriverCivilID,
                            p.DriverName,
                            p.DriverReturnDate.ToString(),
                            p.DriverReturnRemarks,                            
                            p.VehicleQCRejectedDate.ToString(),
                            p.VehicleQCRejectedRemarks,
                            p.TrailerNumber
                        }
                    }
                ).ToArray()
            };

            return Json(JsonData, JsonRequestBehavior.AllowGet);
        }



        //
        // GET: /MissionDetail/Details/5

        public ActionResult Details(long id)
        {
            MissionDetail MissionDetail = repository.GetByID(id);
            if (MissionDetail == null)
                return View("NotFound");
            else
                return View("Details", MissionDetail);
        }

        //
        // GET: /MissionDetail/Create

        public ActionResult Create()
        {
            MissionDetail pf = new MissionDetail();
            //pf.TMR = "TMR-";
            //pf.MissionStatusCode = "1";
            //pf.MissionTypeCode = "1";
            return View(new MissionDetailViewModel(pf));
        }

        //
        // POST: /MissionDetail/Create

        [HttpPost]
        public ActionResult Create(MissionDetail MissionDetail)
        {

            //UpdateModel(MissionDetail);
            try
            {
                if (String.IsNullOrEmpty(MissionDetail.VehicleNumber))
                {
                    ModelState.AddModelError("VehicleNumber", "VehicleNumber is required");
                }

                if (ModelState.IsValid)
                {
                    DriverRepository driverRepository = new DriverRepository();
                    Driver driver = driverRepository.GetByID(MissionDetail.DriverCivilID);
                    if (driver != null)
                    {
                        MissionDetail.DriverNumber = driver.CivilID;
                        MissionDetail.DriverName = driver.FirstName + " " + driver.LastName;
                        MissionDetail.LicenseExpiryDate = driver.DrivingLicenceExpiryDate;
                        MissionDetail.Nationality = driver.Nationality;
                        MissionDetail.PassportNumber = driver.PassportNo;
                        MissionDetail.VisaNumber = driver.ResidencyNo;
                        MissionDetail.VisaExpiryDate = driver.ResidencyExpairyDate;
                    }
                    VehicleRepository vehicleRepository = new VehicleRepository();
                    Vehicle truck = vehicleRepository.GetByID(MissionDetail.VehicleNumber);
                    if (truck != null)
                    {
                        
                        MissionDetail.LicensePlateNumber = truck.LicensePlateNumber;
                        MissionDetail.Model = truck.Model;
                        MissionDetail.TrailerNumber = truck.TrailorNo;
                    }

                    repository.Add(MissionDetail);
                    repository.Save();
                }
                else
                {
                    return View(new MissionDetailViewModel(MissionDetail));
                }

                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("ErrorAddingItem", ex);
                return View(new MissionDetailViewModel(MissionDetail));
            }

        }

        //
        // GET: /MissionDetail/Edit/5

        public ActionResult Edit(long id)
        {
            try
            {
                MissionDetail MissionDetail = repository.GetByID(id);
                if (MissionDetail == null)
                    return View("NotFound");

                return View(new MissionDetailViewModel(MissionDetail));
            }
            catch
            {
                return View();
            }
        }

        //
        // POST: /MissionDetail/Edit/5

        [HttpPost]
        public ActionResult Edit(long id, MissionDetail MissionDetail, string type)
        {
            try
            {
                MissionDetail originalMissionDetail = repository.GetByID(id);
                //Oprations update
                if (type == null)
                {                    
                    DriverRepository driverRepository = new DriverRepository();
                    Driver driver = driverRepository.GetByID(MissionDetail.DriverCivilID);
                    if (driver != null)
                    {
                        originalMissionDetail.DriverCivilID = driver.CivilID;
                        originalMissionDetail.DriverNumber = driver.CivilID;
                        originalMissionDetail.DriverName = driver.FirstName + " " + driver.LastName;
                        originalMissionDetail.LicenseExpiryDate = driver.DrivingLicenceExpiryDate;
                        originalMissionDetail.Nationality = driver.Nationality;
                        originalMissionDetail.PassportNumber = driver.PassportNo;
                        originalMissionDetail.VisaNumber = driver.ResidencyNo;
                        originalMissionDetail.VisaExpiryDate = driver.ResidencyExpairyDate;
                    }
                    VehicleRepository vehicleRepository = new VehicleRepository();
                    Vehicle truck = vehicleRepository.GetByID(MissionDetail.VehicleNumber);
                    if (truck != null)
                    {
                        originalMissionDetail.VehicleNumber = MissionDetail.VehicleNumber;
                        originalMissionDetail.LicensePlateNumber = truck.LicensePlateNumber;
                        originalMissionDetail.Model = truck.Model;
                        originalMissionDetail.TrailerNumber = truck.TrailorNo;
                    }
                }
                else if (type == "outbound")
                {
                    originalMissionDetail.DepartureDate = MissionDetail.DepartureDate;
                    originalMissionDetail.VehicleOutboundMilage = MissionDetail.VehicleOutboundMilage;
                    originalMissionDetail.DepartureRemarks = MissionDetail.DepartureRemarks;
                }
                else if (type == "inbound")
                {
                    originalMissionDetail.VehicleReturnDate = MissionDetail.VehicleReturnDate;
                    originalMissionDetail.VehicleReturnRemarks = MissionDetail.VehicleReturnRemarks;
                    originalMissionDetail.VehicleInboundMilage = MissionDetail.VehicleInboundMilage;
                    originalMissionDetail.DriverReturnDate = MissionDetail.DriverReturnDate;
                    originalMissionDetail.DriverReturnRemarks = MissionDetail.DriverReturnRemarks;
                }
                else if (type == "qcpassregister")
                {
                    originalMissionDetail.VehicleQCPassDate = MissionDetail.VehicleQCPassDate;
                    originalMissionDetail.VehicleQCPassRemarks = MissionDetail.VehicleQCPassRemarks;
                }
                else if (type == "qcrejectedregister")
                {
                    originalMissionDetail.VehicleQCRejectedDate = MissionDetail.VehicleQCRejectedDate;
                    originalMissionDetail.VehicleQCRejectedRemarks = MissionDetail.VehicleQCRejectedRemarks;
                }

                //UpdateModel(MissionDetail);
                repository.Update(originalMissionDetail);
                repository.Save();

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("DataVersionConflict", ex);

                return View(new MissionDetailViewModel(MissionDetail));

            }

        }

        //
        // GET: /MissionDetail/Delete/5

        public ActionResult Delete(long id)
        {
            MissionDetail MissionDetail = repository.GetByID(id);

            return View(MissionDetail);
        }

        //
        // POST: /MissionDetail/Delete/5

        [HttpPost]
        public ActionResult Delete(long id, FormCollection collection)
        {
            try
            {
                MissionDetail MissionDetail = repository.GetByID(id);

                repository.Delete(MissionDetail);
                repository.Save();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }

        }

    }
}
